//
//  TimeInComeViewController.swift
//  TinyShopKeeper
//
//  Created by rimi on 16/6/6.
//  Copyright © 2016年 yuying. All rights reserved.
//

import UIKit

class TimeInComeViewController: UIViewController {

    
    
    
    
    //MARK:--属性Property
    @IBOutlet weak var incomeLabel: UILabel!
    @IBOutlet weak var bottomScrollView: UIScrollView!
    
    //选中的店铺id默认全部选中
    var selectedShopID:String = UserInfo.allShopID()
    //时间数据
    var timeSource:[String] = [String]()
    //收入数据 接口返回的数据是NSNumber类型
    var incomeSource:[NSNumber] = [NSNumber]()
    
    
    //折线图
    var lineCharView:LineCharView!
    
    //结束时间和结束的时间点
    var endTime:String!
    var endTimeHour:Int!
    
    
    //MARK:--LifeCyle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "时段收入分析"
        
        
        self.bottomScrollView.contentSize = CGSizeMake(2014, CGRectGetHeight(self.bottomScrollView.frame))
        self.loadData()
    }
    
    
    //MARK:--网络部分
    //请求：
    func loadData() {
    
        //参数：
        let paramDic:[String:String] = ["shop_id":selectedShopID]
        NetTool.requestX("加载中", urlString: urlAppendGetParams(TIME_INCOME_MAIN_URL), paramDictionary: ["body" : paramDic], successAction: { (responseObject) -> Void in
            print(responseObject)
            MBProgressHUD.hideHUD()
            //数据处理
            self.dealWithData(responseObject["body"] as! [String:AnyObject] )
     
            }) { (error) -> Void in
                
        }
      
    }
    
    //数据处理
    func dealWithData(result:[String:AnyObject]){
        
        let time = result["e_time"] as! String
        
        //时间
        let hourTime = time.substringFromIndex(time.endIndex.advancedBy(-2))
        let hourInt = Int(hourTime)
        endTime = time
        endTimeHour = Int(hourTime)
        //创建时间数组
        createTimeSource(hourInt!)
        incomeSource.removeAll()
        
        //收入字典数据

        let incomeValue = result["value"]
        //判断是数组还是字典
        if ((incomeValue?.isKindOfClass(NSDictionary.self) ) != nil ){
            
            let incomeDic = incomeValue as! NSDictionary
            let incomeValueArray = incomeDic.objectsForKeys(timeSource, notFoundMarker: NSNumber(float: 0))//notFoundMarker: "0"没有对应对的键值对返回的东西就是0
            
            for income in incomeValueArray{
                let incomeValue = income.floatValue
                let incomeNumber = NSNumber(float: incomeValue)
                incomeSource.append(incomeNumber)
            }
            
            
        }else if ((incomeValue?.isKindOfClass(NSArray.self) ) != nil ){
            
            let incomeArray = incomeValue as! [NSNumber]
            incomeSource.appendContentsOf(incomeArray)//在前面这个数组中 添加后面数组的全部元素
        }
        
        
        
        self.incomeSource  .removeAll()
        self.incomeSource .append(NSNumber(float: 20))
        self.incomeSource .append(NSNumber(float: 250))
        self.incomeSource .append(NSNumber(float: 100))
        self.incomeSource .append(NSNumber(float: 330))
        self.incomeSource .append(NSNumber(float: 190))
        self.incomeSource .append(NSNumber(float: 50))
        self.incomeSource .append(NSNumber(float: 300))
        self.incomeSource .append(NSNumber(float: 30))
        self.incomeSource .append(NSNumber(float: 150))
        self.incomeSource .append(NSNumber(float: 10))
        self.incomeSource .append(NSNumber(float: 99))
        self.incomeSource .append(NSNumber(float: 0))
        self.incomeSource .append(NSNumber(float: 10))
        self.incomeSource .append(NSNumber(float: 75))
        self.incomeSource .append(NSNumber(float: 100))
        self.incomeSource .append(NSNumber(float: 300))
        self.incomeSource .append(NSNumber(float: 130))
        self.incomeSource .append(NSNumber(float: 110))
        self.incomeSource .append(NSNumber(float: 180))
        self.incomeSource .append(NSNumber(float: 300))
        self.incomeSource .append(NSNumber(float: 30))
        self.incomeSource .append(NSNumber(float: 150))
        self.incomeSource .append(NSNumber(float: 10))
        self.incomeSource .append(NSNumber(float: 99))
        self.incomeSource .append(NSNumber(float: 109))
        //数据准备好后 需要创建界面去显示它
        //计算所有的和，放到label里面总收入
        var sum = 0
        for i in 0...incomeSource.count-1{
            
            sum = sum + incomeSource[i].integerValue
        }
        self.incomeLabel.text = String(sum)
        
        self.lineCharView = LineCharView(frame: CGRectMake(0,0, 2014, CGRectGetHeight(self.bottomScrollView.frame)-20), callBack: { [unowned self](index) -> Void in
            //[unowned self]弱引用且不为空
            //点击饼状分析图时回调，跳转到 饼状分析图
             self.pushToPieCharView(index)
        })
     
        lineCharView.xLineTitle = timeSource
        lineCharView.yLineValue = incomeSource

        bottomScrollView.addSubview(lineCharView)
        lineCharView.StrokPath()
        
        
        
   }
    
    func pushToPieCharView(index:Int){
        //如果收入为0 提示用户不需跳转
        if incomeSource[index].floatValue < pow(0.1, 0){//pow(0.1, 0) 收入为0（<0.1的6次方） 则会提示用户不需要跳转
            MBProgressHUD.showError("收入为0")
            
        }else{
            print("跳转饼状分析图")
            performSegueWithIdentifier("PushToDetail", sender: NSNumber(integer: index))

        }
        
        
    }
    
    
    
    //创建时间数组
    func createTimeSource(var startIndex:Int){
        
        timeSource.removeAll()
        
        for _ in 0...23{
            timeSource.append("\(startIndex)")
            startIndex += 1
            if startIndex == 24{
                startIndex = 0
            }
        }
    }
    
    
    //MARK:--页面跳转传参数
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        let desVc = segue.destinationViewController as! TimeInComeDetailViewController
        
        desVc.selectedShopId = selectedShopID
        desVc.searchSingleShopSign = !selectedShopID.contain(subStr: ",")//如果包含“,”则为总店铺,反之单店铺为true
        //查询的时间点
        let index = sender as! NSNumber
        desVc.searchTime = searchTimeByIndex(index.integerValue)
        //title
        let timeString = timeSource[index.integerValue]
         desVc.hourIncomeTitle = timeString + ":收入\(incomeSource[index.integerValue])元"
     
    }
    
    //查询的时间点
    func searchTimeByIndex(index:Int) -> String{
        //endtime 
        //endtimehour
        //0~9是当天的时间，10~23是昨天的时间
        var time = endTime
        //
        let selectTimeHour = Int(timeSource[index])!
        time.replaceRange(Range(start: time.endIndex.advancedBy(-2), end: time.endIndex), with: NSString(format: "%02d", selectTimeHour) as String)
        //转成data
        if selectTimeHour >= endTimeHour{
            
            //
            let dateformatter = NSDateFormatter()
            dateformatter.dateFormat = "yyyy-MM-dd-HH"

            //
            let date = dateformatter.dateFromString(time)!
            
            let date2 = date.dateByAddingTimeInterval(-24*1000)
            time = dateformatter.stringFromDate(date2)
            
        }
        
        return time
    }
    
    
    
    
 
}








